package org.example.kafka;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

@Slf4j
public class KafkaProducerExample {

    public static void main(String[] args) {
        // 配置生产者属性
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.236.128:9092");  // Kafka Broker 地址
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); // 键序列化
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); // 值序列化

        // 创建 KafkaProducer 实例
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);

        // 发送消息
        String topic = "test4";
        String key = "key1";
        String value = "Hello, Kafka from Java!";


        int cnt = 10000;
        try {
            for (int k = 0; k < cnt; k++) {
                ProducerRecord<String, String> record = new ProducerRecord<>(topic, String.valueOf(k), value + " " + DateUtil.now() + " " + k);
                // 发送消息
                producer.send(record, (metadata, exception) -> {
                    if (exception != null) {
                        exception.printStackTrace();
                    } else {
                        log.info("Sent message to topic: {},partition:{},with offset:{},value={}", metadata.topic(), metadata.partition(), metadata.offset(), record.value());
                    }
                });

                TimeUnit.MILLISECONDS.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            producer.close();  // 关闭生产者
        }
    }
}
